import React, { useState, useEffect, useContext } from 'react';
import { indexMusicUrl, indexGetSong } from '../../api/indexApi'
import { Slider } from 'antd'
import { CaretRightOutlined, PauseOutlined } from '@ant-design/icons'

// import { ValueContext } from '../../App';

const Player = () => {

    // 加载状态
    let [loading, setLoading] = useState(true)

    // 获取Context的歌曲id值
    // const { value } = useContext(ValueContext)
    // console.log("context" + value);

    // 播放歌曲id值
    // let [songId, setSongId] = useState([])
    let songId = 1997438791

    // 定义播放状态和音频对象
    const [isPlaying, setIsPlaying] = useState(false);
    const [audio] = useState(new Audio());

    // 定义当前时间和音频总时间
    const [currentTime, setCurrentTime] = useState(0);
    const [duration, setDuration] = useState(0);

    // 定义歌曲信息
    const [songMsg, setsSongMsg] = useState([])

    // 获取歌曲播放链接
    useEffect(() => {
        indexMusicUrl(songId, 'exhigh').then((res) => {
            // console.log(res.data.data[0].url);
            if (res.data.data && res.data.data[0]) {
                audio.src = res.data.data[0].url;
            } else {
                console.log("未找到歌曲的链接");
            }
            // if(songId){audio.src = res.data.data[0].url}
            // else{console.log("空songId值")}
        }).catch((err) => { console.log(err); })
    }, [])

    // 获取歌曲信息
    useEffect(() => {
        console.log("获取歌曲信息时" + songId);
        indexGetSong(songId).then((res) => {
            setsSongMsg(res.data.songs)
            // console.log(res.data.songs);
        })
    }, [])

    // 根据播放状态更新音频播放
    useEffect(() => {
        if (isPlaying) {
            audio.play();
        } else {
            audio.pause();
        }
    }, [isPlaying, audio]);

    // 获取音频总时间并监听时间更新
    useEffect(() => {
        // 处理loadedmetadata事件以获取音频总时间
        const handleLoadedMetadata = () => {
            setDuration(audio.duration);
        };
        // 处理timeupdate事件以更新当前时间
        const handleTimeUpdate = () => {
            setCurrentTime(audio.currentTime);
        };

        // 添加事件监听器
        audio.addEventListener('loadedmetadata', handleLoadedMetadata);
        audio.addEventListener('timeupdate', handleTimeUpdate);

        // 在组件卸载时移除事件监听器
        return () => {
            audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
            audio.removeEventListener('timeupdate', handleTimeUpdate);
        };
    }, [audio]);

    // 处理播放/暂停按钮的点击事件
    const handlePlayPause = () => {
        setIsPlaying(!isPlaying);
    };

    // 处理拖动进度条的事件
    const handleTimeSeek = (value) => {

        // console.log(value);
        // console.log('总时间' + duration);
        // console.log(e.target.value);

        const seekTime = (value);

        audio.currentTime = seekTime;

        setCurrentTime(seekTime);

    };

    // 将时间格式化为mm:ss格式
    const formatTime = (time) => {
        const minutes = Math.floor(time / 60);
        const seconds = Math.floor(time % 60)
            .toString()
            .padStart(2, '0');
        return `${minutes}:${seconds}`;
    };

    // 渲染播放器UI
    return (
        <div className='playerContainer'>
            <div className='playSongImg'>
                {
                    songMsg.map((a, i) => { return <img key={i} src={a.al.picUrl} /> })
                }
            </div>

            <div>
                {songMsg.map((a, i) => {
                    let ar = a.ar.map((b, i) => { return <span className='arname' key={i}>{b.name}</span> })
                    return <p className='title' key={i} >{a.name}{ar}</p>
                })}
                <div className='toolsplay'>
                    <button onClick={handlePlayPause} className='handlePlayPause' >{isPlaying ? <PauseOutlined /> : <CaretRightOutlined />}</button>
                    <Slider className='player-progress-bar' defaultValue={0} disabled={false}
                        max={duration}
                        min={0}
                        value={currentTime}
                        onChange={handleTimeSeek}
                        tooltip={{formatter: null}}
                    />
                    <p className='playtime'>
                        <span>{formatTime(currentTime)}</span> / <span>{formatTime(duration)}</span>
                    </p>
                </div>

            </div>

        </div>
    );
};

export default Player;
